package com.play.ballen.home.task

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import com.yuven.baselib.utils.Logger

object StepServiceUtil {

    private lateinit var mStepService: StepService
    private var mBound: Boolean = false

    private val connection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            Logger.i("StepServiceUtil.onServiceConnected")
            val binder = service as StepService.LocalBinder
            mStepService = binder.getService()
            mBound = true
        }

        override fun onServiceDisconnected(arg0: ComponentName) {
            Logger.i("StepServiceUtil.onServiceDisconnected")
            mBound = false
        }
    }

    fun bindService(context: Context) {
        Logger.i("StepServiceUtil.bindService mBound = $mBound")
        if (mBound) {
            return
        }

        //绑定服务
        val intent = Intent(context, StepService::class.java)
        context.bindService(intent, connection, Context.BIND_AUTO_CREATE)
    }

    fun unbindService(context: Context) {
        Logger.i("StepServiceUtil.unbindService mBound = $mBound")
        if (!mBound) {
            return
        }
        context.unbindService(connection)
        mBound = false
    }

    fun stepSensorAvailable(): Boolean {
        Logger.i("StepServiceUtil.stepSensorAvailable mBound = $mBound")
        if (!mBound) {
            return false
        }
        return mStepService.stepSensorAvailable()
    }

    fun registerSensor(context: Context) {
        Logger.i("StepServiceUtil.registerSensor mBound = $mBound")
        if (!mBound) {
            return
        }
        mStepService.registerSensor()

        val intent = Intent(context, StepService::class.java)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {   //8.0后才支持
            context.startForegroundService(intent)
        } else {
            context.startService(intent)
        }
        mStepService.requestStartForeground(context)
    }

    fun unregisterSensor() {
        Logger.i("StepServiceUtil.unregisterSensor mBound = $mBound")
        if (!mBound) {
            return
        }
        mStepService.unregisterSensor()
        mStepService.requestStopForeground()
    }

}